﻿using backend.Entity;
using backend.Enum;
using backend.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace backend.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ProjectController : Controller
    {
        private readonly MyContext _context;
        public ProjectController(MyContext context)
        {
            _context = context;
        }

        // GET api/project/list
        /// <summary>
        /// 项目列表
        /// </summary>
        /// <param name="title"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public MyJsonResult List(string title, int page = 0, int size = 20)
        {
            // 获取当前用户
            User current = _context.Users.FirstOrDefault(a => a.UserName == this.User.Identity.Name);

            IEnumerable<Project> list = null;
            if (current.Role == RoleType.Manager)
            {
                list = _context.Projects.Include(a => a.Users).Include(a => a.Payments).Include(a => a.Parametrics).Include(a => a.Reports).Include(a => a.Attachments);
            }
            else
            {
                list = _context.Projects.Include(a => a.Users).Include(a => a.Payments).Include(a => a.Parametrics).Include(a => a.Reports).Include(a => a.Attachments).Where(a => a.Users.Contains(current));
            }

            int TotalCount = 0;
            IEnumerable<Project> List = null;
            if (list != null)
            {
                if (!string.IsNullOrWhiteSpace(title))
                {
                    list = list.Where(a => a.Title.Contains(title));
                }
                TotalCount = list.Count();
                List = list.Skip((page - 1) * size).Take(size);
            }
            return MyJsonResult.Ok(new { List, TotalCount });
        }

        //  POST api/project
        /// <summary>
        /// 新建项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = RoleType.Manager)]
        public MyJsonResult Post([FromForm] ProjectModel model)
        {
            // 获取当前用户
            User current = _context.Users.FirstOrDefault(a => a.UserName == this.User.Identity.Name);
            if (current.Role != RoleType.Manager)
            {
                return MyJsonResult.Error("无权操作");
            }

            #region 项目
            Project project = new Project()
            {
                Title = model.Title,
                TotalPrice = model.TotalPrice,
                StartDate = model.StartDate,
                EndDate = model.EndDate,
                Organization = model.Organization,
                Address = model.Address,
                Contacter = model.Contacter,
                Tel = model.Tel,
                Users = new List<User> { current }
            };
            #endregion

            #region 附件
            List<Entity.FileInfo> files = null;
            List<Attachment> attachments = null;
            if (model.Files != null)
            {
                files = new List<Entity.FileInfo>();
                attachments = new List<Attachment>();

                DirectoryInfo dir = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "Files", DateTime.Now.ToString("yyyyMMdd")));
                if (!dir.Exists)
                {
                    dir.Create();
                }

                foreach (var item in model.Files)
                {
                    string fileName = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(item.FileName));
                    string path = Path.Combine(dir.FullName, fileName);
                    using (FileStream fs = new FileStream(path, FileMode.Create))
                    {
                        item.CopyTo(fs);
                        fs.Flush();
                        Entity.FileInfo info = new Entity.FileInfo() { Name = item.FileName, Type = item.ContentType, Path = path };
                        files.Add(info);
                        attachments.Add(new Attachment() { FileInfo = info, Project = project });
                    }
                }
            }
            #endregion

            MyJsonResult result = null;
            // 将图片数据写入数据库
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.FileInfos.AddRange(files);
                    _context.Attachments.AddRange(attachments);
                    _context.Projects.Add(project);

                    _context.SaveChanges();

                    tran.Commit();
                    result = MyJsonResult.Ok(project);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result = MyJsonResult.Error(ex.Message);
                }
            }

            return result;
        }

        //  PUT api/project
        /// <summary>
        /// 修改项目基本信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [Authorize(Roles = RoleType.Manager)]
        public MyJsonResult Put([FromQuery, BindRequired] int projectId, [FromForm] ProjectModel model)
        {
            // 获取当前用户
            User current = _context.Users.FirstOrDefault(a => a.UserName == this.User.Identity.Name);
            if (current.Role != RoleType.Manager)
            {
                return MyJsonResult.Error("无权操作");
            }
            // 获取项目实体
            Project project = _context.Projects.SingleOrDefault(a => a.Id == projectId);
            if (project == null)
            {
                return MyJsonResult.Error("数据不存在");
            }

            project.Title = model.Title;
            project.TotalPrice = model.TotalPrice;
            project.StartDate = model.StartDate;
            project.EndDate = model.EndDate;
            project.Organization = model.Organization;
            project.Address = model.Address;
            project.Contacter = model.Contacter;
            project.Tel = model.Tel;

            _context.Projects.Update(project);
            _context.SaveChanges();
            return MyJsonResult.Ok(project);
        }

        //  DELETE api/project
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        [Authorize(Roles = RoleType.Manager)]
        public async Task<MyJsonResult> Delete([BindRequired] int projectId)
        {
            var entity = _context.Projects.Include(a => a.Users).Include(a => a.Payments).Include(a => a.Parametrics).Include(a => a.Reports).Include(a => a.Attachments).SingleOrDefault(t => t.Id == projectId);
            if (entity == null)
            {
                return MyJsonResult.Error("项目信息不存在");
            }

            MyJsonResult result = null;
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.Projects.Remove(entity);
                    await _context.SaveChangesAsync();
                    result = MyJsonResult.Ok(entity);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result = MyJsonResult.Error(ex.Message);
                }
            }
            return result;
        }
    }
}
